import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { department_list, department_add, department_save, department_del } from "@/api/user"
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { deviceDetection } from "@pureadmin/utils";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_department_add: false, // 部门添加

    is_department_edit: false, // 修改
    is_department_del: false, // 删除
  })
  
  // 列表
  const form = reactive({
    key: "",
    page: 1,
    pagesize: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      label: "部门名称",
      prop: "name",
      minWidth: 350,
      align: "left"
    },
    {
      label: "人数",
      prop: "size",
      minWidth: 140,
    },
    {
      label: "负责人",
      prop: "leader_name",
      minWidth: 140,
    },
    {
      label: "分管领导",
      prop: "responsible_leader_name",
      minWidth: 140,
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 300
    },
    {
      label: "创建时间",
      prop: "created_at",
      formatter: ({ created_at }) => dayjs.unix(created_at).format("YYYY-MM-DD HH:mm:ss"),
      minWidth: 180,
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 120
    }
  ]);

  const tableRef = ref();

  function onFullscreen() {
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  function handleSizeChange(val: number) {
    form.pagesize = val;
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  // 对数据操作
  function handleCommand(row, e) {
    if (e == "edit") openDialog('编辑', row);
    else if (e == "delete") handleDelete(row);
  }

  // 删除操作
  function handleDelete(row) {
    ElMessageBox.confirm("确定删除该部门", "重要提示", {
      type: "warning"
    }).then(() => {
      department_del({
        id: row.id
      }).then(res => {
        if (res.code == 1000) {
          message("删除成功", { type: "success" });
          onSearch(); // 刷新表格数据
        } else {
          message(res.msg, { type: "error" });
        }
      });
    }).catch(() => {});
  }

  // 表单
  const formRef = ref();
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}部门`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          leader: row?.leader ?? null,
          leader_name: row?.leader_name ?? "",
          responsible_leader: row?.responsible_leader ?? null,
          responsible_leader_name: row?.responsible_leader_name ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了部门名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            let curForm = JSON.parse(JSON.stringify(curData));
            if (!curForm.id) delete curForm.id;
            delete curForm.leader_name
            delete curForm.responsible_leader_name
            // 表单规则校验通过
            if (title === "新增") {
              department_add(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            } else {
              department_save(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    const result = await department_list(toRaw(form));

    dataList.value = result.data;
    pagination.total = result.count;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/structureManagement/dept/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/structureManagement/dept/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // department_add
      if (homeDataObj.department_add) permissions.is_department_add = true
      // department_table
      if (homeDataObj.department_table) {
        // single
        if (homeDataObj.department_table.single && homeDataObj.department_table.single.length) {
          let permiss = homeDataObj.department_table.single.join(',')
          permissions.is_department_edit = permiss.includes('department_edit') ? true : false
          permissions.is_department_del = permiss.includes('department_del') ? true : false
        }

        let tableRemove = homeDataObj.department_table.remove ? homeDataObj.department_table.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  return {
    permissions,

    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    onSearch,
    resetForm,
    handleOffline,
    onFullscreen,
    handleSizeChange,
    handleCurrentChange,
    handleCommand,
    openDialog
  };
}
